'''
CodeJam Practice 
Created on 2012-12-20

@author: festony
'''

from cj_lib import *
from properties import *

import math
import fractions


curr_file_name = 'B-large-practice'
#curr_file_name = 'B-small-practice'
#curr_file_name = 'test'

# map(int, input_lines.pop(0).split(' '))

def input_dividing_func(input_lines):
    total_case = int(input_lines.pop(0))
    case_inputs = []
    for i in range(total_case):
        input = input_lines.pop(0).split(' ')
        C = int(input.pop(0))
        comb = []
        for i in range(C):
            comb.append(list(input.pop(0)))
        D = int(input.pop(0))
        oppo = []
        for i in range(D):
            oppo.append(list(input.pop(0)))
        N = int(input.pop(0))
        cast = list(input.pop(0))
        case_inputs.append([comb, oppo, cast])
    return case_inputs
    
def process_func(func_input):
    print func_input
    comb, oppo, cast = func_input
    cd = dict()
    od = dict()
    for c in comb:
        if not cd.has_key(c[0]):
            cd[c[0]] = []
        cd[c[0]].append([c[1], c[2]])
        if not cd.has_key(c[1]):
            cd[c[1]] = []
        cd[c[1]].append([c[0], c[2]])
    for o in oppo:
        if not od.has_key(o[0]):
            od[o[0]] = []
        od[o[0]].append(o[1])
        if not od.has_key(o[1]):
            od[o[1]] = []
        od[o[1]].append(o[0])
    print cd, od
    elem = []
    while cast != []:
        print cast, elem
        e = cast.pop(0)
        if len(elem) == 0:
            elem.append(e)
        else:
            combed = False
            if cd.has_key(e):
                cl = cd[e]
                for l in cl:
                    if elem[-1] == l[0]:
                        elem.pop(-1)
                        cast.insert(0, l[1])
                        combed = True
                        break
            if not combed:
                oppoed = False
                if od.has_key(e):
                    ol = od[e]
                    for l in ol:
                        if l in elem:
                            elem = []
                            oppoed = True
                            break
                if not oppoed:
                    elem.append(e)
    return '[' + ', '.join(elem) + ']'

run_proc(process_func, input_dividing_func, curr_working_folder, curr_file_name)


